package api

import (
	"encoding/json"
	"net/http"
	"sort"

	"rt.com/mocktool/mock"
	"rt.com/mocktool/utils/glog"
)

// 排序后的方法
type sortMethodItem []mock.MethodItem

func (a sortMethodItem) Len() int { // 重写 Len() 方法
	return len(a)
}
func (a sortMethodItem) Swap(i, j int) { // 重写 Swap() 方法
	a[i], a[j] = a[j], a[i]
}
func (a sortMethodItem) Less(i, j int) bool { // 重写 Less() 方法， 从大到小排序
	return a[j].TIME < a[i].TIME
}

// loadMethods 加载Mock方法列表
func loadMethods(w http.ResponseWriter, r *http.Request) {
	debugAPI(w, r)
	result := make([]mock.MethodItem, len(mock.Instance.MethodList))
	i := 0
	for _, value := range mock.Instance.MethodList {
		result[i] = mock.MethodItem{
			TYPE: value.TYPE,
			ID:   value.ID,
			Name: value.Name,
			TIME: value.TIME,
		}
		i++
	}
	sort.Sort(sortMethodItem(result))
	resultStr, _ := json.Marshal(result)
	glog.Debug(string(resultStr))
	w.Write(resultStr)
}
